package com.netty.client.socket;

import com.netty.constant.Constants;
import com.netty.model.proto.MessageBodyProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeoutException;


/**
 * @author zl
 * @version 1.0
 * @date 2021/9/24 16:17
 */
public class SocketClientHandler extends SimpleChannelInboundHandler<MessageBodyProto.Model> {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private ImSocketClientHandler imSocketClientHandler;

    public SocketClientHandler(ImSocketClientHandler imSocketClientHandler) {
        this.imSocketClientHandler = imSocketClientHandler;
    }

    //客户端去和服务端连接成功时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel链接成功<<<<<<<<<<<<<<<<<<<<<<");
        imSocketClientHandler.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel注册了<<<<<<<<<<<<<<<<<<<<<<");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel移除了<<<<<<<<<<<<<<<<<<<<<<");
        ctx.close();
        imSocketClientHandler.channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel 捕获到异常了，关闭了{}<<<<<<<<<<<<<<<<<<<<<<", cause);
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (!(evt instanceof IdleStateEvent)) {
            return;
        }
        IdleStateEvent idleEvent = (IdleStateEvent) evt;
        /*
         * 登录成功之后发送心跳
         */
        if (idleEvent.state() == IdleState.WRITER_IDLE) {
            MessageBodyProto.Model.Builder sentBody = MessageBodyProto.Model.newBuilder();
            sentBody.setType(Constants.CmdType.PING);
            sentBody.setTimestamp(System.currentTimeMillis());
            ctx.channel().writeAndFlush(sentBody);
        }
        /*
         * 如果心跳请求发出30秒内没收到响应，则重新连接
         */
        if (idleEvent.state() == IdleState.READER_IDLE) {
            TimeoutException timeoutException = new TimeoutException("响应超时");
            try {
                exceptionCaught(ctx,timeoutException);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageBodyProto.Model model) throws Exception {
        Constants.executorService.submit(new Runnable() {
            @Override
            public void run() {
                switch (model.getType()){
                    case Constants.CmdType.MESSAGE:
                        imSocketClientHandler.channelRead0(ctx.channel(), model);
                        break;
                }
            }
        });
    }
}
